<script setup>
import {ref, onMounted, computed} from 'vue'
import {ElCard, ElTable, ElTableColumn, ElMessage,ElMessageBox} from 'element-plus'

import {
  addAssetCategory,
  getCategoryTree,
  deleteAssetCategory,
  getAssetCategoryDetail,
  updateAssetCategory
} from "@/api/AssetCategory.js"
import {Search, Refresh, Plus, Edit, Delete} from '@element-plus/icons-vue'

// 弹框状态
const formVisible = ref(false)
const title = ref('')

// 资产分类表单数据
const categoryForm = ref({
  name: '',
  parentId: null
})

// 分类树形数据 类别列表
const parentCategories = ref([])


// 是否为编辑状态
const isEditMode = ref(false)

// 当前编辑的分类ID
const currentCategoryId = ref(null)

// 表单验证规则
const rules = {
  name: [
    {required: true, message: '请输入分类名称', trigger: 'blur'}
  ]
}

// // 获取分类树形结构 与 列表数据
const getCategoryTreeData = () => {
  getCategoryTree({
    name: queryForm.value.name
  }).then(res => {
    console.log(res)
    if (res.code === 200) {
      parentCategories.value = res.data
    }
  })
}

// 提交分类表单
const handleSubmit = () => {
  console.log(categoryForm.value, 789)

  // 检查分类名称是否为空
  if (!categoryForm.value.name) {
    ElMessage.warning('请输入分类名称');
    return;
  }
  const apiMethod = isEditMode.value
      ? updateAssetCategory
      : addAssetCategory;

  const requestData = {
    id: currentCategoryId.value,
    name: categoryForm.value.name,
    parentId: categoryForm.value.parentId
  };

  apiMethod(requestData).then(res => {
    if (res.code === 200) {
      ElMessage.success(`${isEditMode.value ? '更新' : '新增'}成功`);
      formVisible.value = false;
      resetForm();
      getCategoryTreeData();
    }
  });
}

// 重置表单
const resetForm = () => {
  isEditMode.value = false;
  console.log(isEditMode.value, "重置表单")
  currentCategoryId.value = null;
  categoryForm.value = {name: '', parentId: null};
}

// 新增资产分类
const addAssetCategoryData = () => {
  formVisible.value = true;
  resetForm()
  title.value = '新增分类'
}

// 获取分类树形结构

// 删除资产分类
const deleteAssetCategoryData = (row) => {
  //console.log(row, "删除")
  ElMessageBox.confirm('确定删除该资产信息吗?', '警告',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
    deleteAssetCategory(row.id).then(res => {
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getCategoryTreeData()
      }
    }).catch(err => {
      ElMessage.error('删除失败')
    })
  }).catch(() => {
    console.log('取消删除')
  })


}

// 编辑资产分类
const editAssetCategoryData = (row) => {
  title.value = '编辑分类'
  //根据id获取分类详情
  getAssetCategoryDetail(row.id).then(res => {
    if (res.code === 200) {
      isEditMode.value = true;
      currentCategoryId.value = row.id;
      categoryForm.value = {
        name: res.data.name,
        parentId: res.data.parentId == "0" ? null : res.data.parentId
      }
      formVisible.value = true
    }
  })
}

// 搜索框绑定的分类名称
const queryForm = ref({
  name: ''
})

// 按分类名称搜索的方法
const handleSearch = () => {
  //判断是否为空
  if (!queryForm.value.name) {
    ElMessage.warning('请输入分类名称');
    return;
  }
  const params = {
    name: queryForm.value.name
  }
  getCategoryTree(params).then(res => {
    if (res.code === 200) {
      parentCategories.value = res.data
    }
  })
}

// 重置搜索条件
const handleReset = () => {
  queryForm.value.name = ''
  getCategoryTreeData()
}

// const displayParentId = computed({
//   get() {
//     return categoryForm.parentId == 0 ? undefined : categoryForm.parentId
//   },
//   set(value) {
//     categoryForm.parentId = value ?? 0;
//   }
// })

onMounted(() => {
  getCategoryTreeData()
})

</script>


<template>

  <!-- 新增搜索框 -->
  <el-form :inline="true" :model="queryForm" style="margin: 10px 0 0 0;">
      <el-form-item>
        <el-space>
          <el-input v-model="queryForm.name" placeholder="请输入分类名称" clearable style="width: 300px"
                    :prefix-icon="Search">
            <template #append>

              <el-button type="primary" style="background: #409eff;color: #ffffff;" :icon="Search"
                         @click="handleSearch">
                搜索
              </el-button>
            </template>
          </el-input>
          <el-button type="primary" plain :icon="Refresh" @click="handleReset">
            重置
          </el-button>
          <el-button plain type="primary" :icon="Plus" @click="addAssetCategoryData">
            新增
          </el-button>
        </el-space>
      </el-form-item>
  </el-form>

  <!-- 新增弹框 -->
  <el-dialog v-model="formVisible" :title="title" width="30%">
    <el-form :model="categoryForm" :rules="rules" label-width="100px">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="categoryForm.name" placeholder="请输入分类名称" clearable/>
      </el-form-item>
      <el-form-item label="上级分类">
        <el-tree-select
            v-model="categoryForm.parentId" placeholder="请选择上级分类"
            :data="parentCategories"
            node-key="id"
            :props="{label:'name',children:'children'}"
            check-strictly
            clearable
            :render-after-expand="false"
            style="width: 200px"
        ></el-tree-select>

      </el-form-item>
      <div class="dialog-footer">
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-form>
  </el-dialog>

  <!-- 表格 默认不展开default-expand-all-->
  <el-table
      :data="parentCategories"
      table-layout="auto"
      height="80%"
      style="margin-top: 10px;"
      row-key="id"
      :default-expand-all="false"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
    <el-table-column prop="name" label="分类名称" align="left"/>
    <el-table-column prop="createTime" label="创建时间" align="center" width="300"/>
    <el-table-column label="操作" align="center" width="180">
      <template #default="scope">
        <el-space>
          <el-link type="primary" :icon="Edit" @click="editAssetCategoryData(scope.row)">
          修改
          </el-link>
          <el-link type="danger" :icon="Delete" @click="deleteAssetCategoryData(scope.row)">
          删除
          </el-link>
        </el-space>
      </template>
    </el-table-column>
  </el-table>

</template>


<style scoped lang='less'>
.mb-4 {
  margin-bottom: 1rem;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

// 添加级联面板样式
:deep(.cascader-popper) {
  .el-cascader-node:not(.is-leaf) > .el-cascader-node__label {
    color: #409EFF;

    &::after {
      content: '（可选）';
      font-size: 12px;
      color: #999;
    }
  }
}

</style>

